<!DOCTYPE>
<html>
<head>
    <title> 像素操作 </title>
    <meta name="Generator" content="EditPlus">
    <meta name="Author" content="">
    <meta name="Keywords" content="">
    <meta name="Description" content="">
    <meta charset="utf-8">
</head>

<body>
    <p>
        <a href="#" onclick="invert();return false;">反色</a>
        <a href="#" onclick="red();return false;">变红</a>
    </p>
    <canvas id="canvas">

    </canvas>
    <script type="text/javascript">
        var img = new Image();
        img.src = 'b1.jpg';
        img.onload = function() {
            draw(this);
        };
        function draw(img){
            var canvas = document.getElementById('canvas');
            var ctx = canvas.getContext('2d');
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
            var imageData = ctx.getImageData(0,0,canvas.width, canvas.height);
            var data = imageData.data;

            window.invert = function() {
                for (var i = 0; i < data.length; i += 4) {
                    data[i]     = 225 - data[i];     // red
                    data[i + 1] = 225 - data[i + 1]; // green
                    data[i + 2] = 225 - data[i + 2]; // blue
                }
                ctx.putImageData(imageData, 0, 0);
            };
            window.red = function() {
                for (var i = 0; i < data.length; i += 4) {
                    data[i]     = 225;     // red
                }
                ctx.putImageData(imageData, 0, 0);
            };
            console.log(data.slice(0,100))

            var grayscale = function() {
                for (var i = 0; i < data.length; i += 4) {
                    var avg = (data[i] + data[i +1] + data[i +2]) / 3;
                    data[i]     = avg; // red
                    data[i + 1] = avg; // green
                    data[i + 2] = avg; // blue
                }
                ctx.putImageData(imageData, 0, 0);
            };
        }
    </script>
</body>
</html>
